package com.yx.musicplayer.ui.base;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;

import com.yx.baselibrary.base.BaseAppCompatActivity;
import com.yx.baselibrary.eventbus.EventCenter;
import com.yx.baselibrary.utils.StatusBarUtil;
import com.yx.musicplayer.R;
import com.yx.musicplayer.aidl.IMusicAidlInterface;
import com.yx.musicplayer.util.MusicPlayerServiceUtil;
import com.yx.musicplayer.ui.fragment.PlayBarFragment;

/**
 * Created by yx on 2017/10/31 0031.
 */

public abstract class BaseActivity extends BaseAppCompatActivity implements ServiceConnection {
    private PlayBarFragment playBarFragment; //底部播放控制栏
    private MusicPlayerServiceUtil.ServiceToken mToken;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mToken = MusicPlayerServiceUtil.bindToService(this, this);
    }

    @Override
    public boolean isApplyTranslucent() {
        return true;
    }

    @Override
    public void setTranslucentStatus() {
        StatusBarUtil.setTranslucentStatus(this, android.R.color.holo_red_dark);
    }

    @Override
    public boolean isBindEventBusHere() {
        return false;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void onEventComming(EventCenter eventCenter) {

    }

    /**
     * @param show 显示或关闭底部播放控制栏
     */
    protected void showQuickControl(boolean show) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (show) {
            if (playBarFragment == null) {
                playBarFragment =new PlayBarFragment();
                ft.add(R.id.container, playBarFragment).commitAllowingStateLoss();
            } else {
                ft.show(playBarFragment).commitAllowingStateLoss();
            }
        } else {
            if (playBarFragment != null) {
                ft.hide(playBarFragment).commitAllowingStateLoss();
            }
        }
    }


    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        MusicPlayerServiceUtil.mService = IMusicAidlInterface.Stub.asInterface(iBinder);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        MusicPlayerServiceUtil.mService = null;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Unbind from the service
        unbindService();
        try {
//            unregisterReceiver(mPlaybackStatus);
        } catch (final Throwable e) {
        }

    }

    public void unbindService() {
        if (mToken != null) {
            MusicPlayerServiceUtil.unbindFromService(mToken);
            mToken = null;
        }
    }
}
